package com.bootdo.coach.api;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.coach.domain.TabDevice;
import com.bootdo.coach.domain.TabMsg;
import com.bootdo.coach.domain.TabUser;
import com.bootdo.coach.result.ResponseEntityUtil;
import com.bootdo.coach.service.TabDeviceService;
import com.bootdo.coach.service.TabMsgService;
import com.bootdo.coach.service.TabUserService;

/**
 * 接口
 * @author Administrator
 *
 */
@RequestMapping("msg")
@RestController
public class MsgApi {
    private static final Logger logger = LoggerFactory.getLogger(MsgApi.class);
    
	@Autowired
	private TabMsgService msgService;
	@Autowired
	private TabDeviceService deviceService;
	@Autowired
	private TabUserService userService;
    
    @GetMapping("/sendMsg")
    @ResponseBody
    public Map<String, Object> sendMsg(String msg) {

    	logger.info("服务器收到消息:" + msg);
    	return ResponseEntityUtil.getSucEntity("服务器成功收到消息");
    }
    
    
	@GetMapping("/getMsg")
	@ResponseBody
	public void getMsg(String account, HttpServletResponse response) {
		
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	if (account == null) {
    		paramMap = new HashMap<String, Object>();
        	paramMap.put("code", -1);
        	paramMap.put("msg", "参数必填");
        	responseText(response, JSONObject.toJSONString(paramMap));
    		return ;
		}
//    	List<TabUser> users = userService.selectByAccount(account);
//    	if (users == null || users.isEmpty()) {
//    		paramMap = new HashMap<String, Object>();
//        	paramMap.put("code", -1);
//        	paramMap.put("msg", "用户不存在");
//        	responseText(response, JSONObject.toJSONString(paramMap));
//    		return ;
//		}
//    	TabUser user = users.get(0);
    	
    	//修改设备的online
    	List<TabDevice> list = deviceService.selectBySerialNumber(account);
    	if (list == null || list.isEmpty()) {
    		paramMap = new HashMap<String, Object>();
        	paramMap.put("code", -1);
        	paramMap.put("msg", "设备不存在");
        	responseText(response, JSONObject.toJSONString(paramMap));
    		return ;
		}
    	TabDevice device = list.get(0);
    	device.setOnline(1);
    	device.setTotalOnlineMinute(device.getTotalOnlineMinute() + 1);
    	Calendar calendar = Calendar.getInstance();
    	calendar.setTime(new Date());
    	calendar.add(Calendar.MINUTE, 3);//三分钟下线
    	device.setExpireTime(calendar.getTime());
    	deviceService.updateByPrimaryKeySelective(device);
    	
    	//device_type_id产品id，	0表示全部类型
    	//send_type		0:指定用户,1:指定产品
    	TabMsg tabMsg = null;
    	// 通过指定发送类型找消息，sengType=1, deviceTypeId=0
    	//找出最新得一条
    	paramMap = new HashMap<String, Object>();
    	paramMap.put("sengType", 1);
    	paramMap.put("deviceTypeId", 0);
    	tabMsg = msgService.findByMap(paramMap);
    	// 通过指定发送类型找消息，sengType=1, deviceTypeId != 0
    	//找出最新得一条
    	paramMap = new HashMap<String, Object>();
    	paramMap.put("sengType", 1);
    	paramMap.put("deviceTypeId", device.getDeviceTypeId());
    	TabMsg tabMsg2 = msgService.findByMap(paramMap);
    	if (tabMsg2 != null) {
    		if (tabMsg == null) {
        		tabMsg = tabMsg2;
    		}else {
				if (tabMsg.getId().longValue() < tabMsg2.getId().longValue()) {
					tabMsg = tabMsg2;
				}
			}
		}
//    	// 通过指定发送类型找消息，sengType=0, userId != 0
//    	//找出最新得一条
//    	paramMap = new HashMap<String, Object>();
//    	paramMap.put("sengType", 0);
//    	paramMap.put("userId", user.getId());
//    	TabMsg tabMsg3 = msgService.findByMap(paramMap);
//    	if (tabMsg3 != null) {
//    		if (tabMsg == null) {
//        		tabMsg = tabMsg3;
//    		}else {
//				if (tabMsg.getId().longValue() < tabMsg3.getId().longValue()) {
//					tabMsg = tabMsg3;
//				}
//			}
//		}

    	String content = tabMsg == null ? "" : tabMsg.getContent();
    	paramMap = new HashMap<String, Object>();
    	paramMap.put("code", 0);
    	paramMap.put("msg", "");
    	paramMap.put("deviceContent", content);
    	responseText(response, JSONObject.toJSONString(paramMap));
    }
	
	private void responseText(HttpServletResponse response,String txt) {
		response.reset();
		response.setCharacterEncoding("GBK");  
	    response.setContentType("application/json; charset=GBK"); 
	    PrintWriter out = null;  
	    try {  
	        out = response.getWriter();  
	        out.append(txt);
	        out.flush();
	    } catch (IOException e) {  
	        e.printStackTrace();
	    } finally {  
	        if (out != null) {  
	            out.close();  
	        }  
	    }  
	}

}
